% Purpose: Calculate texture measurementB from Veggie Vision
% Date: 11/18/2012
% Author: R. Dutka
function [output] = Run_MeasurementB(mask, colorBand)
% subsample image?
%subsampledImage = colorBand(1:2:end,1:2:end,:);
% [rows,columns] = size(mask);
% R = zeros(rows*columns, 2);
% index = 1;
% for a=1:rows
%    for b=1:columns
%     if mask(a, b) == 1
%         R(index,:) = [a, b];
%         index = index + 1;
%     end
%    end
% end
% %concat matrix (remove zeros)
% R( ~any(R,2), : ) = [];

[rows cols] = size(colorBand);
pixelIntensity = zeros(1, 8);
pixelAvg = 0;
deviation = zeros(sum(mask(:)), 1);
deviation = double(deviation);

[r,c] = find(mask);
R = horzcat(r,c);
for i = 1:sum(mask(:))
    % determine x,y coordinates of segmented region R
    x = R(i,1);
    y = R(i,2);
    % check boundaries
    if x - 1 > 0 && y - 1 > 0 
        pixelIntensity(1, 1) = colorBand(x-1, y-1);
    end
    if y - 1 > 0
        pixelIntensity(1, 2) = colorBand(x, y-1);
    end
    if x + 1 < rows && y - 1 > 0
        pixelIntensity(1, 3) = colorBand(x+1, y-1);
    end
    if x - 1 > 0
        pixelIntensity(1, 4) = colorBand(x-1, y);
    end
    if x + 1 < rows
        pixelIntensity(1, 5) = colorBand(x+1, y);
    end
    if x - 1 > 0 && y + 1 < cols
        pixelIntensity(1, 6) = colorBand(x-1, y+1);
    end
    if y + 1 < cols
        pixelIntensity(1, 7) = colorBand(x, y+1);
    end
    if x + 1 < rows && y + 1 < cols
        pixelIntensity(1, 8) = colorBand(x+1, y+1);
    end
    % remove any pixels we skipped
    pixelIntensity( ~any(pixelIntensity), : ) = [];
    pixelAvg = sum(pixelIntensity) / length(pixelIntensity);
    if isempty(pixelIntensity) == 0
        deviation(i,1) = abs(pixelAvg-double(colorBand(x, y)));
    else
        deviation(i,1) = 0;
    end
   
    pixelIntensity = zeros(1,8);
end

output = deviation;